class Solution {
public:
    int fun(string& s,char a,char b){
        int ans = 0;
        int freqA = 0;
        int freqB = 0;
        bool hasB = 0;
        for(char ch:s){
            if(ch == a){
                freqA++;
            }else if(ch == b){
                freqB++;
                hasB = true;
            }
            if(hasB){
                ans = max(ans,freqA-freqB);
            }
            if(freqA<freqB){
                freqA = 0;
                freqB = 0;
                hasB = false;
            }
        }
        return ans;
    }
    int largestVariance(string s) {
        int ans = 0;
        string t = s;
        std::reverse(t.begin(), t.end());
        for(char a='a';a<='z';a++){
            for(char b='a';b<='z';b++){
                if(a==b){
                    continue;
                }
                ans = max(ans,fun(s,a,b));
                ans = max(ans,fun(t,a,b));
            }
        }
        return ans;
    }
};